package com.neuedu.shop.common;

import com.alibaba.fastjson.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Date;

@Slf4j
public class COSUtils {
    // 1. 初始化用户身份信息（secretId, secretKey）。
    private final static String COS_SECRETID = "AKIDkFTTvAEi55r2lFc2Raw3tQoxpRoiAtBG";
    private final static String COS_SECRETKEY = "yfWzf4B2fQuEI8j12numRpmjPwbdroRM";
    private final static String COS_REGION = "ap-beijing";
    private final static String  BUCKET_NAME= "yhtest-1302727948";

    public static COSClient init() {
        COSCredentials cred = new BasicCOSCredentials(COS_SECRETID, COS_SECRETKEY);
        Region region = new Region(COS_REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    public static String upload(String path) {
        // 指定要上传的文件
        File localFile = new File(path);
        String localPath=localFile.getPath();
        String ext=localPath.substring(localPath.indexOf("."),localPath.length());
        // 指定要上传到的存储桶
        // 指定要上传到 COS 上对象键
        String key = new Long(new Date().getTime()).toString()+ext;
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, localFile);
        PutObjectResult putObjectResult = init().putObject(putObjectRequest);
        log.info(JSON.toJSONString(putObjectResult));
//        https://yhtest-1302727948.cos.ap-beijing.myqcloud.com/1605169285546
        return "https://"+BUCKET_NAME+".cos."+COS_REGION+".myqcloud.com/"+key;
    }
}
